import time
import requests

from common.logging_use import Logger
from config import API_LOG


class ApiRequest:
    logger = Logger.init_log_config(__name__,API_LOG)
    def __init__(self,base_url,timeout):
        self.base_url = base_url
        self.timeout = timeout
        self.session = requests.Session()


    def _send_request(self,method,url,data=None,**kwargs):
        start_time = time.time()
        full_url = self.base_url + url
        method = str(method).lower()
        if method == 'get':
            resp = self.session.request(method,full_url,timeout=self.timeout,params=data,**kwargs)
        elif method in["post","put"]:
            headers = kwargs.get("headers",{})
            if "Content-Type" not in headers:
                headers["Content-Type"] = "application/json"
                kwargs["headers"] = headers
            resp = self.session.request(method, full_url, timeout=self.timeout, data=data, **kwargs)
        elif method == 'delete':
            resp = self.session.request(method=method, timeout=self.timeout, url=full_url, **kwargs)
        else:
            ApiRequest.logger.error("不支持的请求方法")
            raise ValueError("不支持的请求方法")

        try:
            resp.raise_for_status()
            ApiRequest.logger.info(f"链接：{url},方式为：{method}，请求头：{kwargs.get('headers')},请求体：{data}")
            return resp
        except requests.exceptions.RequestException as e:
            ApiRequest.logger.error(f"Request to {full_url} failed: {e}")
            raise



    def get(self, url, params=None, **kwargs):
        return self._send_request("get", url, data=params, **kwargs)

    def post(self, url, data=None, **kwargs):
        return self._send_request("post", url, data=data, **kwargs)

    def put(self, url, data=None, **kwargs):
        return self._send_request('put', url, data=data, **kwargs)

    def delete(self, url, **kwargs):
        return self._send_request("delete", url, **kwargs)


if __name__ == '__main__':
    api = ApiRequest("https://kdtx-test.itheima.net", 10)
    print(api.get("/api/captchaImage"))